package com.hzlj.position.locate.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.fz.common.base.core.date.DateUtils;
import com.fz.common.base.dto.PageParamDTO;
import com.fz.common.base.dto.QueryPageResultDTO;
import com.fz.common.base.exception.PubError;
import com.fz.common.base.exception.PubException;
import com.fz.common.dict.annotation.DictConvert;
import com.google.common.collect.Lists;
import com.hzlj.position.config.common.dto.jzJbxxDeviceBind.JzJbxxDeviceBindSimpleQueryParamDTO;
import com.hzlj.position.config.config.PositionConfig;
import com.hzlj.position.config.service.JzJbxxDeviceBindService;
import com.hzlj.position.locate.common.dto.abnMissingJzry.AbnMissingJzryQueryParamDTO;
import com.hzlj.position.locate.common.dto.abnMissingJzry.AbnMissingJzryQueryResultDTO;
import com.hzlj.position.locate.common.dto.abnMissingJzryNotice.AbnMissingJzryNoticeAddDTO;
import com.hzlj.position.locate.common.dto.positionNewestEffective.PositionNewestEffectiveSimpleResultDTO;
import com.hzlj.position.locate.common.model.AbnMissingJzry;
import com.hzlj.position.locate.converter.AbnMissingJzryConverter;
import com.hzlj.position.locate.dao.AbnMissingJzryDao;
import com.hzlj.position.locate.service.AbnMissingJzryNoticeService;
import com.hzlj.position.locate.service.AbnMissingJzryService;
import com.hzlj.position.locate.service.PositionNewestEffectiveService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.hzlj.position.config.config.IdConfig.POSITION_ID_GEN;

/**
 * 定位分析-疑似失联人员(AbnMissingJzry)表服务接口
 *
 * @author makejava
 * @date 2024-06-25 14:40:45
 */
@Slf4j
@Service
public class AbnMissingJzryServiceImpl implements AbnMissingJzryService {
    @Resource
    private AbnMissingJzryDao abnMissingJzryDao;
    @Resource
    private PositionNewestEffectiveService positionNewestEffectiveService;
    @Resource
    private JzJbxxDeviceBindService jzJbxxDeviceBindService;
    @Resource
    private PositionConfig positionConfig;
    @Resource
    private AbnMissingJzryNoticeService abnMissingJzryNoticeService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void abn() {
        if (!positionConfig.getAbn().getMissing()) {
            return;
        }
        //开始结束时间
        Date startDay = positionConfig.getAbn().missingYesterday() ? DateUtils.yesterday() : DateUtils.now();
        Date endDay = DateUtils.now();
        Date startTime = DateUtils.parseDate(startDay, "yyyy-MM-dd " + positionConfig.getAbn().getMissingStartTime());
        Date endTime = DateUtils.parseDate(endDay, "yyyy-MM-dd " + positionConfig.getAbn().getMissingEndTime());

        List<String> positionJzIds = positionNewestEffectiveService.listJzIds(startTime, endTime);
        List<String> bindJzIds = Lists.newArrayList();
        //可以是多个jgCodes
        String[] missingJgCodes = positionConfig.getAbn().getMissingJgCodes();
        //查询参数
        JzJbxxDeviceBindSimpleQueryParamDTO params = new JzJbxxDeviceBindSimpleQueryParamDTO()
                .setMkh(!positionConfig.getAbn().getExcludeMkh())
                .setQzcs(!positionConfig.getAbn().getExcludeQzcs());
        //查询绑定人员
        if (ObjectUtil.isEmpty(missingJgCodes)) {
            bindJzIds = jzJbxxDeviceBindService.listJzIds(params);
        } else {
            for (String missingJgCode : missingJgCodes) {
                params.setJgCode(missingJgCode);
                bindJzIds.addAll(jzJbxxDeviceBindService.listJzIds(params));
            }
        }
        Collection<String> jzIds = CollectionUtil.subtract(bindJzIds, positionJzIds);
        this.saveAbnMissing(jzIds, startTime, endTime);
    }

    private void saveAbnMissing(Collection<String> jzIds, Date startTime, Date endTime) {
        if (ObjectUtil.isEmpty(jzIds)) {
            return;
        }
        Date endTimeHMS = DateUtils.parseDate(endTime, DateUtils.DATE_FULL_FORMAT);
        List<List<String>> jzIdsSplit = CollectionUtil.split(jzIds, 500);
        List<AbnMissingJzryNoticeAddDTO> notices = Lists.newArrayList();
        for (List<String> item : jzIdsSplit) {
            List<AbnMissingJzry> adds = item.stream().map(jzId -> {
                PositionNewestEffectiveSimpleResultDTO position = positionNewestEffectiveService.getPositionNewestEffective(jzId);
                AbnMissingJzry abn = new AbnMissingJzry();
                abn.setId(POSITION_ID_GEN.nextIdStr());
                abn.setJzId(jzId);
                abn.setStartTime(startTime);
                abn.setEndTime(endTimeHMS);
                abn.setBelongDay(DateUtil.beginOfDay(endTime));
                abn.setCreateTime(new Date());
                if (position != null) {
                    abn.setLastPosition(position.getPosition());
                    abn.setLastPositionId(position.getPositionId());
                    abn.setLastPositionTime(position.getPositionTime());
                }
                //通知项
                notices.add(new AbnMissingJzryNoticeAddDTO()
                        .setJzId(abn.getJzId())
                        .setMissingId(abn.getId())
                        .setBelongDay(abn.getBelongDay())
                );
                return abn;
            }).collect(Collectors.toList());
            abnMissingJzryDao.saveBatch(adds);
        }
        abnMissingJzryNoticeService.saveAbnMissingJzryNotice(notices);
    }

    /**
     * 通过id查询单条数据
     */
    @Override
    public AbnMissingJzryQueryResultDTO getAbnMissingJzryById(String id) {
        AbnMissingJzry abnMissingJzry = this.abnMissingJzryDao.getById(id);
        if (Objects.isNull(abnMissingJzry)) {
            throw new PubException(PubError.NO_OBJECT_FOUND);
        }
        return AbnMissingJzryConverter.from(abnMissingJzry);
    }


    /**
     * 查询列表：不分页
     */
    @Override
    @DictConvert
    public List<AbnMissingJzryQueryResultDTO> listAbnMissingJzry(AbnMissingJzryQueryParamDTO dto) {
        return this.abnMissingJzryDao.listAbnMissingJzry(dto);
    }

    /**
     * 查询列表：分页
     */
    @Override
    @DictConvert
    public QueryPageResultDTO<AbnMissingJzryQueryResultDTO> pageAbnMissingJzry(AbnMissingJzryQueryParamDTO dto, PageParamDTO page) {
        return this.abnMissingJzryDao.pageAbnMissingJzry(dto, page);
    }
}
